<?php

namespace App\Http\Controllers\Api;

use Carbon\Carbon;
use App\Models\User;
use App\Models\LoginLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class AuthorizationController extends ApiController
{
    /**
     *
     * @return mixed
     */
    public function wxLogin(Request $request)
    {
        // 获取openid
        if ($request->code) {
            $wx_info = $this->easyWechatGetSession($request->code);
            $session_key = $wx_info['session_key'];
            Cache::put($wx_info['openid'], $session_key, 3600);
        }
        //登录失败情况
        if (!$request->openid && empty($wx_info['openid'])) {
            if (isset($wx_info) && !empty($wx_info['errmsg'])) {
                return $this->success($wx_info['errmsg'], 'error');
            } else {
                return $this->success('微信登录失败', 'error');
            }
        }
        $openid = empty($wx_info['openid']) ? $request->openid : $wx_info['openid'];
        $userInfo = User::where('openid', $openid)->first();
        if ($userInfo) {
            //登录
            $userInfo->last_login_ip = $this->getClientIP();
            $userInfo->last_login_time = Carbon::now();
            $userInfo->save();
            // 登录日志
            $loginlog = new LoginLog(['login_ip' => $this->getClientIP(), 'login_time' => Carbon::now(), 'remark' => '小程序登录']);
            $userInfo->login_logs()->save($loginlog);
        } else {
            if ($request->input('rawData')) {
                //如果包含详细信息则执行 注册
                $userInfo = $this->register($request, $openid);
            }
            else{
                $data['openid'] =$wx_info['openid'];
                $data['msg']='微信未注册';
                return $this->success($data,'error');
            }
        }
        // 直接创建token
        $token = $userInfo->createToken($openid)->accessToken;
        $data['token'] = $token;
        $data['userInfo'] = $userInfo;
        return $this->success($data);
    }
    // 注册
    public function register($request, $openid)
    {
        //  进行基本验证
        $user_info =  \GuzzleHttp\json_decode($request->input('rawData'), true);
        //注册信息
        $newUser = [
            'openid' => $openid, //openid
            'nickname' => $user_info['nickName'], // 昵称
            'avatar' => $user_info['avatarUrl'], //头像
            'password' => bcrypt($openid),
            'last_login_ip' => $this->getClientIP(),
            'last_login_time' => Carbon::now(),
        ];
        $userInfo = User::create($newUser);
        // 日志
        $loginlog = new LoginLog(['login_ip' => $this->getClientIP(), 'login_time' => Carbon::now(), 'remark' => '小程序注册']);
        $userInfo->login_logs()->save($loginlog);
        // 返回用户信息
        return $userInfo;
    }

    public function easyWechatGetSession($code)
    {
        $app = app('wechat.mini_program');
        return $app->auth->session($code);
    }

    // 解密微信信息
    public function decryptWechatChatData($openid,$iv,$encryptData)
    {
        $session = Cache::get($openid);
        $decryptedData = $app->encryptor->decryptData($session, $iv, $encryptData);
        return $decryptedData;
    }
}
